package com.pan;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
 * 缓存相关的配置。
 *
 * @author starkpan
 * @date 2019-06-18 09:29:03
 */
@Configuration
public class CacheConfiguration {


    /**
     * cacheManager只能有一个，如果有多个的话，会报如下错误。
     *  No CacheResolver specified, and no unique bean of type CacheManager found.
     *  Mark one as primary or declare a specific CacheManager to use.
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {
        return RedisCacheManager.builder(redisConnectionFactory)
                .cacheDefaults(redisCacheConfiguration())
                .build();
    }

    @Bean
    public RedisCacheConfiguration redisCacheConfiguration() {
        return RedisCacheConfiguration.defaultCacheConfig()
                //确定缓存key序列化方式
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(stringRedisSerializer()))
                //确定缓存value序列化方式
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonSerializer()))
                //缓存有效时间为1天
                .entryTtl(Duration.ofDays(1))
                // 不缓存空值
                .disableCachingNullValues();
    }

    /**
     * 提供stringRedis序列化方法
     * @return
     */
    @Bean
    public RedisSerializer<String> stringRedisSerializer() {
        return new StringRedisSerializer();
    }

    /**
     * 提供json序列化方法
     * @return
     */
    @Bean
    public RedisSerializer<Object> jackson2JsonSerializer() {
        return new GenericJackson2JsonRedisSerializer();
    }


}
